#ifndef QMLADB_H
#define QMLADB_H

#include <QtDeclarative/QDeclarativeItem>
#include <QObject>
#include <QProcess>

class QMLAdb : public QDeclarativeItem
{
    Q_OBJECT
    Q_DISABLE_COPY(QMLAdb)

    Q_ENUMS(StateType)
    Q_ENUMS(CommandType)
    Q_ENUMS(RebootType)

    Q_PROPERTY(QString adbPath READ adbPath WRITE setAdbPath NOTIFY adbPathChanged)
    Q_PROPERTY(QString deviceName READ deviceName WRITE setDeviceName NOTIFY deviceNameChanged)

public:
    enum StateType{
        Idle
        , Executing
    };
    enum CommandType{
        Push
        , Pull
        , Devices
        , ShellMkDir
        , ShellCommand
        , Reboot
    };
    enum RebootType{
        RebootNormal
        , RebootBootLoader
        , RebootRecovery
    };

    QMLAdb(QDeclarativeItem *parent = 0);
    ~QMLAdb();
    
    QString adbPath() const;
    void setAdbPath(const QString &adbpath);
    QString deviceName() const;
    void setDeviceName(const QString &devicename);

    Q_INVOKABLE bool postAdbDevices();
    Q_INVOKABLE bool postAdbPush(const QString &localFile, const QString &remoteFile);
    Q_INVOKABLE bool postAdbReboot(const RebootType type);

    Q_INVOKABLE bool postMkDir(const QString &remoteDir);
    Q_INVOKABLE bool postShellCommand(const QString &command);

signals:
    void finished(int exitCode, CommandType mode, QStringList result);
    void adbPathChanged();
    void deviceNameChanged();

public slots:
    void readFromStdout();
    void processStateChanged(QProcess::ProcessState newState);
    void processExited(int exitCode, QProcess::ExitStatus exitStatus);
    void processError(QProcess::ProcessError error);

private:
    QProcess m_process;
    StateType m_state;      //状態（待機中or実行中）
    CommandType m_mode;        //実行モード

    QString m_adbPath;
    QString m_deviceName;

    QStringList m_tempMkDir;        //mkdirする時の作成リスト
    QByteArray m_tempWriteData;     //shell接続時に送信するデータ

    QStringList parseDevices(QString str);  //adb devicesの結果をパースする
    QStringList parsePush(QString str);     //adb pushの結果をパースする
    bool postMkDir();                       //adb shell mkdirの繰り返し用

    QString fixPathChar(QString path);      //Winの場合は/を\に直す

};

QML_DECLARE_TYPE(QMLAdb)


#endif // QMLADB_H
